class Solution
{
public:
    int minimumOperations(vector<vector<int>> &grid)
    {
        int m = grid.size();
        int n = grid[0].size();

        vector<vector<int>> count(n, vector<int>(10));
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                count[j][grid[i][j]]++;
            }
        }

        vector<vector<int>> dp(n, vector<int>(10, INT_MAX));
        for (int i = 0; i < 10; ++i)
        {
            dp[0][i] = m - count[0][i];
        }

        for (int i = 1; i < n; ++i)
        {
            for (int j = 0; j < 10; ++j)
            {
                for (int k = 0; k < 10; ++k)
                {
                    if (j == k)
                    {
                        continue;
                    }

                    dp[i][j] = min(dp[i][j], dp[i - 1][k] + m - count[i][j]);
                }
            }
        }
        return *min_element(dp[n - 1].begin(), dp[n - 1].end());
    }
};